class DSU:
    def __init__(self):
        self.parent = {}

    def find(self, node):
        if node not in self.parent:
            self.parent[node] = node
        if self.parent[node] == node:
            return node
        else:
            parent = self.find(self.parent[node])
            self.parent[node] = parent

            return parent

    def union(self, x, y):
        px = self.find(x)
        py = self.find(y)
        self.parent[py] = px


class Solution:
    def countServers(self, grid: list) -> int:
        dsu = DSU()
        counter = {}
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    dsu.union(i, j + 251)
            counter[i] = 0

        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    counter[dsu.find(i)] += 1

        res = 0
        for val in counter.values():
            if val > 1:
                res += val
        return res
